<template>
  <el-select v-bind="$attrs" v-model="value" clearable filterable @change="change">
    <el-option
      v-for="item in languageOptions"
      :key="item.id"
      :label="item.name"
      :value="getValue(item)"
    >
      {{ item.name }} ({{ item.short_name }})
    </el-option>
  </el-select>
</template>
<script setup>
import useCommonStore from "@/store/modules/common";

const commonStore = useCommonStore();
const languageOptions = computed(() => {
  if (!commonStore.languageOptions) {
    commonStore.getLanguageList();
  }
  return commonStore.languageOptions || [];
});

const props = defineProps({
  modelValue: [String, Number, Array],
  valueKey: {
    type: String,
    default: "id",
  },
});

const value = computed(() => {
  return props.modelValue;
});

const getValue = (item) => {
  return props.valueKey === "item" ? item : item[props.valueKey];
};

const emit = defineEmits(["update:modelValue"]);
const change = (val) => {
  const item = languageOptions.value.find((i) => i[props.valueKey] == val);
  emit("change", item?.short_name || "");
  emit("changeItem", item || "");
  emit("update:modelValue", val);
};
</script>
